package com.construction.api.exception;

import cn.hutool.jwt.JWTException;
import com.construction.api.domain.model.result.BaseResult;
import com.construction.api.enums.ResultEnum;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * @author dybin
 * @Date: 2021/7/1 23:53
 */
@RestControllerAdvice
@ResponseStatus(HttpStatus.OK)
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        String msg = ex.getMessage();
        // 特殊处理
        if (ex instanceof BindException || ex instanceof MethodArgumentNotValidException) {
            msg = wrapperBindingResult(((BindException) ex).getBindingResult());
        }
        return super.handleExceptionInternal(ex, BaseResult.of(status.value(), msg), headers, status, request);
    }

    @ExceptionHandler({BusinessException.class})
    public BaseResult businessException(BusinessException e) {
        return wrapperCommonResult(e, e.getResultEnum());
    }

    @ExceptionHandler({Exception.class})
    public BaseResult exception(Exception e) {
        return wrapperCommonResult(e, ResultEnum.BAD_REQUEST);
    }

    @ExceptionHandler({JWTException.class})
    public BaseResult jwtException(JWTException e) {
        return wrapperCommonResult(e, ResultEnum.UNAUTHORIZED);
    }

    private BaseResult wrapperCommonResult(Exception e, ResultEnum resultEnum) {
        return ObjectUtils.isEmpty(e.getMessage())
                ? BaseResult.of(resultEnum)
                : BaseResult.of(resultEnum.getCode(), resultEnum.getMsg() + ": " + e.getMessage());
    }

    private String wrapperBindingResult(BindingResult bindingResult) {
        StringBuilder msg = new StringBuilder();
        for (ObjectError error : bindingResult.getAllErrors()) {
            msg.append(", ");
            if (error instanceof FieldError) {
                msg.append(((FieldError) error).getField()).append(": ");
            }
            msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
        }
        return msg.toString();
    }
}
